<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
* 
*/

class Ads_model extends MY_Model {
    private $table = 'ads';

    /**
     * 获取多条数据
     * @param  array
     * @param  boolean
     * @return [array]
     */
    public function get_lists($select = [], $where = [], $join = '') {
        $this->db
            ->select($select)
            ->order_by('ads.sort ASC, ads.id ASC');
        if ($join) {
            $this->db->select('adscate.name AS cate_name')->join('adscate', 'adscate.id = ads.adscate_id', 'LEFT');
        }
        return $this->db->get_where($this->table, $where)->result_array();
    }

    /**
     * 获取所有数据总数
     * @param  array
     * @param  array
     * @return [int]
     */
    public function total_rows($where = [], $join = '') {
        if ($join) {
            $this->db->join('adscate', 'adscate.id = ads.adscate_id', 'LEFT');
        }
        return $this->db->select('id')->get_where($this->table, $where)->num_rows();
    }

    /**
     * [insert 新增]
     * @return [type] [description]
     */
    public function insert() {
        $data = $this->get_data('ads');
        if (empty($data)) {
            return 0;
        }
        
        $this->db->insert($this->table, $data);
        return $this->db->insert_id();
    }
    
    /**
     * 获取一行数据
     * @param  array
     * @param  array
     * @return [array]
     */
    public function get_one($where = [], $select = []) {
        if (empty($where)) {
            return [];
        }
        return $this->db->select($select)->get_where($this->table, $where)->row_array();
    }

    /**
     * [update 更新]
     * @param  array  $where [description]
     * @return [type]        [description]
     */
    public function update($where = []) {
        if (empty($where)) {
            return 0;
        }
        
        $data = $this->get_data('ads');
        if (empty($data)) {
            return 0;
        }

        $this->db->update($this->table, $data, $where);
        return $this->db->affected_rows();
    }

    /**
     * [delete 删除]
     * @param  array  $where [description]
     * @return [type]        [description]
     */
    public function delete($where = []) {
        if (empty($where)) {
            return 0;
        }

        $lists = $this->get_lists(['image'], $where);

        $this->db->delete($this->table, $where);
        $affected_rows = $this->db->affected_rows();
        if (! empty($affected_rows)) {
            unlink($lists);
        }
        return $affected_rows;
    }
}
